﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendEMail.aspx.cs" Inherits="CRMWeb.Pages.SendEMail" %>

<!DOCTYPE html>

<html>
<head id="Head1" runat="server">
    <title>Send EMAIL</title>
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script src="../tiny_mce/tiny_mce.js"></script>
    <script src="/Scripts/AppDetail.js"></script>
    <link href="../Css/uploadify.css" rel="stylesheet" />
    <script src="../Scripts/jquery.uploadify.js"></script>
    <script src="/Scripts/ProgressBar.js"></script>
    <script src="../Scripts/jquery.uploadifive.js"></script>
    <link href="../Css/uploadifive.css" rel="stylesheet" />
    <link href="/Css/ProgressStyle.css" rel="stylesheet" />
    <style type="text/css">
        body
        {
            font: 13px Arial, Helvetica, Sans-serif;
        }

        #queue
        {
            border: 1px solid #E5E5E5;
            height: 40px;
            overflow: auto;
            margin-bottom: 10px;
            padding: 0 3px 3px;
            width: 268px;
        }
    </style>
</head>
<body>
    <form id="sendmail" runat="server">
        <div id="pnlMail" title="Send E-Mail" class="easyui-panel" style="width: auto; height: auto">
            <table style="width: 100%; height: auto">
                <tr>
                    <td colspan="2">
                        <div class="sms_dropdown">
                            <label style="text-align: left">Email Template:</label>
                            <select class="easyui-combotree" id="cmbUc_emailTemp" style="width: 520px;"
                                data-options="url:'/WebServices/EmailTemplate.ashx?method=DisplayTemplateNode', onSelect:selectEmailTemplate">
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>

                    <td style="text-align: left; width: 50%">
                        <div class="sms_dropdown">
                            <label style="text-align: left">From:</label>
                            <input class="easyui-combobox" id="cmbUc_from" runat="server" name="EmailId" style="width: 195px;" data-options="url:'/WebServices/EmailTemplate.ashx?method=SelectAllEmailId',
					        valueField:'EmailId',
					        textField:'EmailId',
					        multiple:false,
                            			onSelect:getPwd,
                              			selected:true" />
                            <input type="hidden" id="hdnfrompw" runat="server" />
                        </div>
                        <div class="sms_dropdown">
                            <label style="text-align: left">Send To:</label>
                            <select class="easyui-combogrid" id="cmbSendToUc" style="width: 195px; height: 22px;" runat="server" name="FullName" data-options="  
                            panelWidth: 195,
                            multiple: true,
                            idField: 'Email',  
                            textField: 'FullName',
                            editable:true,  
                            url: '/WebServices/SelectAppAndContacts.ashx?app_id=' + getQuerystring('app_id', '') + '&ContactID=' +getQuerystring('contact_id', ''),
                            columns: [[
                                {field:'ck',checkbox:true},
                                {field:'FullName',width:80},
                            ]],
                            onSelect:getSelectionsForEmail, 
                            onUnselect:getUnselectForEmail,
                            fitColumns: true">
                            </select>
                        </div>
                        <div class="fitsem sms_dropdown">
                            <label style="text-align: left">Email Address:</label>
                            <input id="txttomailid" name="txtMailto" type="text" class="easyui-validatebox" onchange="validateEmail($('#txttomailid').val())" />
                            <span id="spnEmail" style="display: none; color: red; font-size: 14px;"><b>*</b> </span>
                        </div>
                        <div class="fitem sms_dropdown">
                            <label style="text-align: left">Subject:</label>
                            <input id="txtSubject" name="txt_sub" type="text" class="easyui-validatebox" />
                        </div>
                    </td>
                    <td style="text-align: left; width: 50%">
                        <div class="fitem sms_dropdown">
                            <label style="width: 100px; text-align: left">Attachment:</label>
                            <asp:FileUpload ID="file_uploads" runat="server" />
                            <input type="hidden" id="hdnAttachment" runat="server" />
                            <table id="attachedfiles" style="text-align: right"></table>
                        </div>
                        <div class="fitem sms_dropdown">
                            <label style="width: 100px; text-align: left">Drag Here:</label>
                            <input id="file_upload" name="file_upload" type="file" style="display: none" multiple="true">
                            <div id="queue" style="margin-left: 4px;"></div>
                            <input type="hidden" id="hdndragfiles" runat="server" />
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="divProgressBar" class='dimmer' style="left: 329px; top: 190px;">
                            <table border='0' align='center' cellpadding='0' cellspacing='0' class='progress_tab'>
                                <tr>
                                    <td ondblclick='void(0);' onmouseover='over=true;' onmouseout='over=false;'>&nbsp</td>
                                    <td>&nbsp</td>
                                    <td colspan='4'>&nbsp</td>
                                    <td>&nbsp</td>
                                </tr>
                                <tr>
                                    <td colspan='4'>&nbsp</td>
                                    <td>
                                        <img src='/Media/ajax-loader-blue.gif' alt='' /></td>
                                    <td colspan='4'>&nbsp</td>
                                    <td>Processing</td>
                                </tr>
                                <tr>
                                    <td>&nbsp</td>
                                    <td>&nbsp</td>
                                    <td>&nbsp</td>
                                </tr>
                            </table>
                        </div>
                    </td>
                    <td></td>
                </tr>
            </table>
            <div data-options="region:'center'" style="padding: 10px; height: 65%" class="emailbox">
                <asp:TextBox ID="txtMailMessage" runat="server" TextMode="MultiLine" Width="100%"></asp:TextBox>
            </div>
            <div data-options="region:'south',border:false" style="text-align: right; padding: 5px; margin-right: 20px;">
                <label id="lblerror" style="font-size: 14px; font-weight: bold; padding-right: 60px; color: red;" runat="server"></label>
                <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="sendEmail();">Send</a>
            </div>
            <asp:ScriptManager ID="sm1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
            <input type="hidden" runat="server" id="hdnEmailOpr" />
            <input type="hidden" id="hdnNodeValInPage" runat="server" />
        </div>
    </form>
    <script type="text/javascript">
        function isMailValidation() {
            if ($('#txttomailid').val() == '' || $('#txtMailMessage').val() == '') {
                return false;
            }
        }
        function validateEmail(elementValue) {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (emailPattern.test(elementValue) == true) {
                $('#spnEmail').hide();
                return true;
            }
            else {
                $('#spnEmail').show();
                $('#txttomailid').focus();
                return false;
            }
        }
        function IsValidate() {
            var flag = true;
            //if ($('#cmbUc_emailTemp').combobox('getValue') == '') {
            //    $.messager.alert('Morgan CRM', 'Select Email Template ', 'info');
            //    return flag = false;
            //}
            if ($('#cmbUc_from').combobox('getValue') == '') {
                $.messager.alert('Morgan CRM', 'Select From ', 'info');
                return flag = false;
            }
            if ($('#txttomailid').val() == '') {
                $.messager.alert('Morgan CRM', 'Enter Email Address ', 'info');
                return flag = false;
            }
            if ($('#txtSubject').val() == '') {
                $.messager.alert('Morgan CRM', 'Enter Subject ', 'info');
                return flag = false;
            }
            return flag;
        }
        tinyMCE.init({
            mode: "textareas",
            elements: "txtMailMessage",
            theme: "advanced",
            relative_urls: true,
            remove_script_host: false,
            convert_urls: true,
            plugins: "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,help,code,|,forecolor,backcolor",
            setup: function (ed) {
                ed.onInit.add(function (ed) {
                    ed.getDoc().body.style.fontSize = '13pt';
                });
            }
        });
        window.onresize = function () {
            $('#pnlMail').panel('resize', {
                width: window.innerWidth,
                height: window.innerHeight
            });
        }
        $(document).ready(function () {

            $('#cmbUc_emailTemp').combotree({
                onClick: function (node) {
                    if (!$('#cmbUc_emailTemp').tree('isLeaf', node.target)) {
                        $('#cmbUc_emailTemp').combotree('setValues', '');
                        var t = $('#cmbUc_emailTemp').combotree('tree');
                        t.tree('toggle', node.target);
                        var p = $('#cmbUc_emailTemp').combotree('panel');
                        p.panel('open');
                    }
                }
            });

            $('#txttomailid').val(getQuerystring('email', ''));
            $("#cmbSendToUc").combogrid('setValue', getQuerystring('email', ''));
            //var frommail = '<%=ConfigurationManager.AppSettings["fromemail"].ToString()%>';
            //$('#cmbUc_from').val(frommail);
            $('#pnlMail').panel('resize', {
                width: window.innerWidth,
                height: window.innerHeight
            });
            $('#cmbUc_emailTemp').combobox('textbox').bind('click', function () {
                $('#cmbUc_emailTemp').combobox('showPanel');
            });
            $('#cmbUc_from').combobox('textbox').bind('click', function () {
                $('#cmbUc_from').combobox('showPanel');
            });
            $('#cmbSendToUc').combobox('textbox').bind('click', function () {
                $('#cmbSendToUc').combobox('showPanel');
            });
        });
        var addEmails;
        function getSelectionsForEmail() {
            var ss = [];
            var r = $('#cmbSendToUc').combogrid('grid');
            var rows = r.datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                ss.push(row.Email);
            }
            addEmails = ss.join(',');
            $("#txttomailid").val(addEmails);
        }
        function getUnselectForEmail() {
            addEmails = '';
            $("#txttomailid").val('');
        }
    </script>
    <script type="text/javascript">
        var EmailOpr;
        $(window).load(
            $(function () {
                $("#file_uploads").uploadify({
                    'swf': '../Media/uploadify.swf',
                    'uploader': '/WebServices/AttachmentUpload.ashx',
                    'cancelImg': '../Media/cancel.png',
                    'fileSizeLimit': '25MB',
                    'buttonText': 'Attach Files',
                    'fileDesc': 'Image Files',
                    'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.txt;*.pdf',
                    'multi': true,
                    'auto': true,
                    'onUploadComplete': function (file) {
                        var attchVal = fileName;
                        $("#hdnAttachment").val(attchVal);
                    }
                });
            })
        );
        //Drag and drop
        $(function () {
            $('#file_upload').uploadifive({
                'auto': true,
                'queueID': 'queue',
                'fileSizeLimit': '25MB',
                'uploadScript': '/WebServices/Upload.ashx',
                'onUploadComplete': function (file, data) {
                    $("#hdndragfiles").val(data);
                }
            });
        });
        var userPwdVal;
        function getPwd(rec) {
            userPwdVal = rec.Password;
        }

        function onSuccess() {
            $("#txttomailid").val('');
            $("#cmbUc_from").val('');
            $("#txtSubject").val('');
            tinymce.get('txtMailMessage').setContent('');
            window.opener.location.reload();
            $.messager.alert('Morgan CRM', 'E-Mail sent successfully');
            window.close();
        }
        $(document).ready(function () {
            EmailOpr = document.getElementById('hdnEmailOpr').value;
            $.ajax({
                type: "get",
                url: "/WebServices/EmailTemplate.ashx?method=SelectPasswordDef",
                success: function (data) {
                    data = data.replace("[{", " ");
                    data = data.replace("}]", " ");
                    data = data.replace("}", " ");
                    data = data.replace("{", " ");
                    data = data.replace("}", " ");
                    data = data.replace("{", " ");
                    var arr = data.split(",");
                    for (i = 0; i < arr.length; i++) {
                        var arr1 = arr[i].split(':');
                        var key = arr1[0].replace('"', ' ').replace('"', ' ');
                        key = key.replace(/^\s+|\s+$/g, '');
                        key.replace(/^\s+|\s+$/g, '');
                        var value = arr1[1].replace('"', ' ').replace('"', ' ');
                        value = value.replace(/^\s+|\s+$/g, '');
                        if (key == "EmailId") {
                            var setId = " " + value;
                            $("#cmbUc_from").combobox('setValue', setId);
                        }
                        if (key == "setPwd") {
                            userPwdVal = value;
                        }
                    }
                },
                error: function (data) {
                }
            });
        });


        //Send Email Function
        function sendEmail() {
            if (IsValidate()) {
                var password = userPwdVal;
                if (password == null) {
                    $.messager.alert('Morgan CRM', 'Oops your password is not found!');
                    HideProgressBarEvent();
                }
                else {
                    DisplayProgessBarEvent();
                    var fromName = $("#cmbUc_from").combobox('getText');
                    var toName = $("#txttomailid").val();
                    var attachmentFile = $("#hdnAttachment").val();
                    var attachmentsDrag = $("#hdndragfiles").val();
                    var subject = $("#txtSubject").val();
                    var bodyContent = tinyMCE.get('txtMailMessage').getContent({ format: 'raw' });

                    $.ajax({
                        type: "Post",
                        data: { fromName: fromName, password: password, toName: toName, attachmentFile: attachmentFile, attachmentsDrag: attachmentsDrag, subject: subject, bodyContent: bodyContent },
                        url: "/WebServices/SendEmailToUsers.ashx",
                        success: function (result) {
                            HideProgressBarEvent();
                            var Description = '';
                            if (result.length > 0) {
                                result = result.replace(/,$/, '');
                                Description = "To: " + toName + '</br>' + "<span style=\"color:red;font-weight:bold\">Attachments:-  " + result + " </span> </br>" + tinyMCE.get('txtMailMessage').getContent({ format: 'raw' });
                            }
                            else
                                Description = "To: " + toName + '</br>' + tinyMCE.get('txtMailMessage').getContent({ format: 'raw' });

                            Description = encodeURIComponent(Description);
                            document.getElementById("attachedfiles").innerHTML = '';
                            document.getElementById("queue").innerHTML = '';
                            //To update history table:
                            var ContactID = getQuerystring('contact_id', 0);
                            var AppID = getQuerystring('app_id', 0);
                            var currentDate = new Date()
                            var day = currentDate.getDate()
                            var month = currentDate.getMonth() + 1
                            var year = currentDate.getFullYear()
                            var HistoryDate = month + "/" + day + "/" + year;
                            var currentTime = new Date()
                            var hours = currentTime.getHours()
                            var minutes = currentTime.getMinutes()
                            var seconds = currentTime.getSeconds();
                            var HistoryTime = hours + ':' + minutes + ':' + seconds;
                            var Action = 'Email Sent';
                            var Operator = EmailOpr;

                            if (AppID > 0) {
                                PageMethods.saveNewHistory('Application','0', HistoryDate, HistoryTime, Action, Operator, Description,AppID);
                                setTimeout(function () {
                                    onSuccess();
                                }, 100);
                            }
                            else if (ContactID > 0) {
                                PageMethods.saveNewHistory('Contact', ContactID, HistoryDate, HistoryTime, Action, Operator, Description, '0');
                                setTimeout(function () {
                                    onSuccess();
                                }, 100);
                            }
                            else
                                onSuccess();
                        }
                    });
                }
            }
        }
    </script>
    <script type="text/javascript">

        //Get NodeId:
        var OperatorId = '';
        $(document).ready(function () {

            OperatorId = document.getElementById('hdnNodeValInPage').value;
        });

        function getQuerystring(key, defaultValue) {
            if (defaultValue == null) defaultValue = "";
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
            var qs = regex.exec(window.location.href);
            if (qs == null)
                return defaultValue;
            else {
                return qs[1];
            }
        }

        function selectEmailTemplate(node) {
            var currentTemplateId = node.id;
            $.ajax({
                url: "/WebServices/EmailTemplate.ashx?method=GetEmailTemplateContentById",
                contentType: "application/json; charset=utf-8",
                data: { EmailTemplateId: currentTemplateId },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, result) {
                        if (getQuerystring('contact_id', '') != '') {
                            showContactData(result.TemplateFormat);
                        }
                        else if (getQuerystring('app_id', '') != '') {
                            showApplicationData(result.TemplateFormat);
                        }
                        else {
                            tinymce.get('txtMailMessage').setContent(decodeURIComponent(result.TemplateFormat));
                        }
                        $('#txtSubject').val(result.emailsubject);
                    });
                },
                error: function () {
                    alert("Error while getting template.");
                }
            });
        }

        function showContactData(EMAILTemplateFormat) {
            $.ajax({
                url: "/WebServices/ApplicationContact.ashx?method=ApplicationContactSelect",
                contentType: "application/json; charset=utf-8",
                data: { 'ContactID': getQuerystring('contact_id', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        var decodeTemp = decodeURIComponent(EMAILTemplateFormat);

                        //ClientFileds
                        decodeTemp = decodeTemp.replace('%ContactID (Client)%', rec.ContactID);
                        decodeTemp = decodeTemp.replace('%FirstName (Client)%', rec.FirstName);
                        decodeTemp = decodeTemp.replace('%MiddleName (Client)%', rec.MiddleName);
                        decodeTemp = decodeTemp.replace('%SurName (Client)%', rec.SurName);
                        decodeTemp = decodeTemp.replace('%Title (Client)%', rec.Title);
                        decodeTemp = decodeTemp.replace('%Mobile (Client)%', rec.Mobile);
                        decodeTemp = decodeTemp.replace('%HomePhone (Client)%', rec.HomePhone);
                        decodeTemp = decodeTemp.replace('%Email (Client)%', rec.Email);
                        decodeTemp = decodeTemp.replace('%DriverLicense (Client)%', rec.DriverLicense);
                        decodeTemp = decodeTemp.replace('%Citizenship (Client)%', rec.Citizenship);
                        decodeTemp = decodeTemp.replace('%DateBirth (Client)%', rec.DateBirth);
                        decodeTemp = decodeTemp.replace('%Street (Client)%', rec.Street);
                        decodeTemp = decodeTemp.replace('%Suburb (Client)%', rec.Suburb);
                        decodeTemp = decodeTemp.replace('%State (Client)%', rec.State);
                        decodeTemp = decodeTemp.replace('%PostCode (Client)%', rec.PostCode);
                        decodeTemp = decodeTemp.replace('%ResidencePeriod (Client)%', rec.ResidencePeriod);
                        decodeTemp = decodeTemp.replace('%ResidenceLength (Client)%', rec.ResidenceLength);
                        decodeTemp = decodeTemp.replace('%Dependant (Client)%', rec.Dependant);
                        decodeTemp = decodeTemp.replace('%app_ResidentialStatus (Client)%', rec.app_ResidentialStatus);
                        decodeTemp = decodeTemp.replace('%app_number (Client)%', rec.app_number);
                        decodeTemp = decodeTemp.replace('%app_id (Client)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%NumberFromAppinfo (Client)%', rec.NumberFromAppinfo);
                        decodeTemp = decodeTemp.replace('%Memo (Client)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%CreateDate (Client)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Client)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%DupwithContact (Client)%', rec.DupwithContact);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Client)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%Role (Client)%', rec.Role);
                        decodeTemp = decodeTemp.replace('%Relationship (Client)%', rec.Relationship);
                        decodeTemp = decodeTemp.replace('%WorkPhone (Client)%', rec.WorkPhone);
                        decodeTemp = decodeTemp.replace('%FaxNumber (Client)%', rec.FaxNumber);
                        decodeTemp = decodeTemp.replace('%Email1 (Client)%', rec.Email1);
                        decodeTemp = decodeTemp.replace('%PostalAddress (Client)%', rec.PostalAddress);
                        decodeTemp = decodeTemp.replace('%IncomeType (Client)%', rec.IncomeType);
                        decodeTemp = decodeTemp.replace('%SelfEmpTypeofEntity (Client)%', rec.SelfEmpTypeofEntity);
                        decodeTemp = decodeTemp.replace('%SelfEmpBusinessName (Client)%', rec.SelfEmpBusinessName);
                        decodeTemp = decodeTemp.replace('%SelfEmpABN (Client)%', rec.SelfEmpABN);
                        decodeTemp = decodeTemp.replace('%SelfEmpNatureofBusiness (Client)%', rec.SelfEmpNatureofBusiness);
                        decodeTemp = decodeTemp.replace('%SelfEmpPhone (Client)%', rec.SelfEmpPhone);
                        decodeTemp = decodeTemp.replace('%SelfEmpAddress (Client)%', rec.SelfEmpAddress);
                        decodeTemp = decodeTemp.replace('%KinsName (Client)%', rec.KinsName);
                        decodeTemp = decodeTemp.replace('%KinsRelationship (Client)%', rec.KinsRelationship);
                        decodeTemp = decodeTemp.replace('%KinsContactNumber (Client)%', rec.KinsContactNumber);
                        decodeTemp = decodeTemp.replace('%Notes (Client)%', rec.Notes);
                        decodeTemp = decodeTemp.replace('%EmpEmployer (Client)%', rec.EmpEmployer);
                        decodeTemp = decodeTemp.replace('%EmpOccupation (Client)%', rec.EmpOccupation);
                        decodeTemp = decodeTemp.replace('%EmpJobPosition (Client)%', rec.EmpJobPosition);
                        decodeTemp = decodeTemp.replace('%EmpEmployerPhone (Client)%', rec.EmpEmployerPhone);
                        decodeTemp = decodeTemp.replace('%EmpContactPerson (Client)%', rec.EmpContactPerson);
                        decodeTemp = decodeTemp.replace('%EmpWorkAddress (Client)%', rec.EmpWorkAddress);
                        decodeTemp = decodeTemp.replace('%comesfrom (Client)%', rec.comesfrom);

                        //Loan Fileds
                        decodeTemp = decodeTemp.replace('%LoanID (Loan)%', rec.LoanID);
                        decodeTemp = decodeTemp.replace('%LoanNumber (Loan)%', rec.LoanNumber);
                        decodeTemp = decodeTemp.replace('%PaymentPeriod (Loan)%', rec.PaymentPeriod);
                        decodeTemp = decodeTemp.replace('%DrawDownDate (Loan)%', rec.DrawDownDate);
                        decodeTemp = decodeTemp.replace('%LoanStatusID (Loan)%', rec.LoanStatusID);
                        decodeTemp = decodeTemp.replace('%LoanTerm (Loan)%', rec.LoanTerm);
                        decodeTemp = decodeTemp.replace('%FirstPaymentDue (Loan)%', rec.FirstPaymentDue);
                        decodeTemp = decodeTemp.replace('%LowerRate (Loan)%', rec.LowerRate);
                        decodeTemp = decodeTemp.replace('%HigherRate (Loan)%', rec.HigherRate);
                        decodeTemp = decodeTemp.replace('%InterestMethod (Loan)%', rec.InterestMethod);
                        decodeTemp = decodeTemp.replace('%app_id (Loan)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%Lender (Loan)%', rec.Lender);
                        decodeTemp = decodeTemp.replace('%Product (Loan)%', rec.Product);
                        decodeTemp = decodeTemp.replace('%Type (Loan)%', rec.Type);
                        decodeTemp = decodeTemp.replace('%Purpose (Loan)%', rec.Purpose);
                        decodeTemp = decodeTemp.replace('%LoanAmount (Loan)%', rec.LoanAmount);
                        decodeTemp = decodeTemp.replace('%DishonorFee (Loan)%', rec.DishonorFee);
                        decodeTemp = decodeTemp.replace('%Memo (Loan)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%NewDDRDate (Loan)%', rec.NewDDRDate);
                        decodeTemp = decodeTemp.replace('%BankAccDate (Loan)%', rec.BankAccDate);
                        decodeTemp = decodeTemp.replace('%PaymentSchDate (Loan)%', rec.PaymentSchDate);
                        decodeTemp = decodeTemp.replace('%EffectiveDate (Loan)%', rec.EffectiveDate);
                        decodeTemp = decodeTemp.replace('%DefaultNotice (Loan)%', rec.DefaultNotice);
                        decodeTemp = decodeTemp.replace('%DoubleChecked (Loan)%', rec.DoubleChecked);
                        decodeTemp = decodeTemp.replace('%CreateDate (Loan)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Loan)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%LastResult (Loan)%', rec.LastResult);
                        decodeTemp = decodeTemp.replace('%EzidebitRefNo (Loan)%', rec.EzidebitRefNo);
                        decodeTemp = decodeTemp.replace('%OperatorName%', EmailOpr);
                        tinymce.get('txtMailMessage').setContent(decodeTemp);
                    });
                }
            });
        }

        var FsName = [];
        var MidName = [];
        var LastName = [];
        var strFsName;
        var strMidName;
        var strLsName;
        function showApplicationData(EMAILTemplateFormat) {
            $.ajax({
                url: "/WebServices/ApplicationProfileDataSelect.ashx",
                contentType: "application/json; charset=utf-8",
                data: { 'app_id': getQuerystring('app_id', '') ,'OperatorId':OperatorId},
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        var decodeTemp = decodeURIComponent(EMAILTemplateFormat);

                        //ApplicationFileds
                        decodeTemp = decodeTemp.replace('%app_id (Application)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Application)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%app_result (Application)%', rec.app_result);
                        decodeTemp = decodeTemp.replace('%ResultID (Application)%', rec.ResultID);
                        decodeTemp = decodeTemp.replace('%LoadNo (Application)%', rec.LoadNo);
                        decodeTemp = decodeTemp.replace('%Folder (Application)%', rec.Folder);
                        decodeTemp = decodeTemp.replace('%AwaitDocs (Application)%', rec.AwaitDocs);
                        decodeTemp = decodeTemp.replace('%NoInApplication (Application)%', rec.NoInApplication);
                        decodeTemp = decodeTemp.replace('%OfferedAmount (Application)%', rec.OfferedAmount);
                        decodeTemp = decodeTemp.replace('%DesiredAmount (Application)%', rec.DesiredAmount);
                        decodeTemp = decodeTemp.replace('%amountMoto (Application)%', rec.amountMoto);
                        decodeTemp = decodeTemp.replace('%amoutProperties (Application)%', rec.amoutProperties);
                        decodeTemp = decodeTemp.replace('%TextAwaitDoc (Application)%', rec.TextAwaitDoc);
                        decodeTemp = decodeTemp.replace('%PurposeSummary (Application)%', rec.PurposeSummary);
                       // decodeTemp = decodeTemp.replace('%Unsubscribe_Ad (Application)%', rec.Unsubscribe_Ad);
                        decodeTemp = decodeTemp.replace('%Memo (Application)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%LenderID (Application)%', rec.LenderID);
                        decodeTemp = decodeTemp.replace('%OutSrcLenderVal (Application)%', rec.OutSrcLenderVal);
                        decodeTemp = decodeTemp.replace('%ReferrerID (Application)%', rec.ReferrerID);
                        decodeTemp = decodeTemp.replace('%ReferrerVal (Application)%', rec.ReferrerVal);
                        decodeTemp = decodeTemp.replace('%CreatedDate (Application)%', rec.CreatedDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Application)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%comesfrom (Application)%', rec.comesfrom);
                        decodeTemp = decodeTemp.replace('%securities (Application)%', rec.securities);

                        //ClientFileds
                        decodeTemp = decodeTemp.replace('%ContactID (Client)%', rec.ContactID);

                        //First applicant name:
                        FsName.push(rec.FirstName);
                        strFsName = FsName[0];
                        decodeTemp = decodeTemp.replace('%FirstName (Client)%', strFsName);


                        MidName.push(rec.MiddleName);
                        strMidName = MidName[0];
                        decodeTemp = decodeTemp.replace('%MiddleName (Client)%', strMidName);

                        LastName.push(rec.SurName);
                        strLsName = LastName[0];
                        decodeTemp = decodeTemp.replace('%SurName (Client)%', strLsName);

                        decodeTemp = decodeTemp.replace('%Title (Client)%', rec.Title);
                        decodeTemp = decodeTemp.replace('%Mobile (Client)%', rec.Mobile);
                        decodeTemp = decodeTemp.replace('%HomePhone (Client)%', rec.HomePhone);
                        decodeTemp = decodeTemp.replace('%Email (Client)%', rec.Email);
                        decodeTemp = decodeTemp.replace('%DriverLicense (Client)%', rec.DriverLicense);
                        decodeTemp = decodeTemp.replace('%Citizenship (Client)%', rec.Citizenship);
                        decodeTemp = decodeTemp.replace('%DateBirth (Client)%', rec.DateBirth);
                        decodeTemp = decodeTemp.replace('%Street (Client)%', rec.Street);
                        decodeTemp = decodeTemp.replace('%Suburb (Client)%', rec.Suburb);
                        decodeTemp = decodeTemp.replace('%State (Client)%', rec.State);
                        decodeTemp = decodeTemp.replace('%PostCode (Client)%', rec.PostCode);
                        decodeTemp = decodeTemp.replace('%ResidencePeriod (Client)%', rec.ResidencePeriod);
                        decodeTemp = decodeTemp.replace('%ResidenceLength (Client)%', rec.ResidenceLength);
                        decodeTemp = decodeTemp.replace('%Unsubscribe_Ad (Client)%', rec.Unsubscribe_Ad);
                        decodeTemp = decodeTemp.replace('%Dependant (Client)%', rec.Dependant);
                        decodeTemp = decodeTemp.replace('%app_ResidentialStatus (Client)%', rec.app_ResidentialStatus);
                        decodeTemp = decodeTemp.replace('%app_number (Client)%', rec.app_number);
                        decodeTemp = decodeTemp.replace('%app_id (Client)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%NumberFromAppinfo (Client)%', rec.NumberFromAppinfo);
                        decodeTemp = decodeTemp.replace('%Memo (Client)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%CreateDate (Client)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Client)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%DupwithContact (Client)%', rec.DupwithContact);
                        decodeTemp = decodeTemp.replace('%deletedFlag (Client)%', rec.deletedFlag);
                        decodeTemp = decodeTemp.replace('%Role (Client)%', rec.Role);
                        decodeTemp = decodeTemp.replace('%Relationship (Client)%', rec.Relationship);
                        decodeTemp = decodeTemp.replace('%WorkPhone (Client)%', rec.WorkPhone);
                        decodeTemp = decodeTemp.replace('%FaxNumber (Client)%', rec.FaxNumber);
                        decodeTemp = decodeTemp.replace('%Email1 (Client)%', rec.Email1);
                        decodeTemp = decodeTemp.replace('%PostalAddress (Client)%', rec.PostalAddress);
                        decodeTemp = decodeTemp.replace('%IncomeType (Client)%', rec.IncomeType);
                        decodeTemp = decodeTemp.replace('%SelfEmpTypeofEntity (Client)%', rec.SelfEmpTypeofEntity);
                        decodeTemp = decodeTemp.replace('%SelfEmpBusinessName (Client)%', rec.SelfEmpBusinessName);
                        decodeTemp = decodeTemp.replace('%SelfEmpABN (Client)%', rec.SelfEmpABN);
                        decodeTemp = decodeTemp.replace('%SelfEmpNatureofBusiness (Client)%', rec.SelfEmpNatureofBusiness);
                        decodeTemp = decodeTemp.replace('%SelfEmpPhone (Client)%', rec.SelfEmpPhone);
                        decodeTemp = decodeTemp.replace('%SelfEmpAddress (Client)%', rec.SelfEmpAddress);
                        decodeTemp = decodeTemp.replace('%KinsName (Client)%', rec.KinsName);
                        decodeTemp = decodeTemp.replace('%KinsRelationship (Client)%', rec.KinsRelationship);
                        decodeTemp = decodeTemp.replace('%KinsContactNumber (Client)%', rec.KinsContactNumber);
                        decodeTemp = decodeTemp.replace('%Notes (Client)%', rec.Notes);
                        decodeTemp = decodeTemp.replace('%EmpEmployer (Client)%', rec.EmpEmployer);
                        decodeTemp = decodeTemp.replace('%EmpOccupation (Client)%', rec.EmpOccupation);
                        decodeTemp = decodeTemp.replace('%EmpJobPosition (Client)%', rec.EmpJobPosition);
                        decodeTemp = decodeTemp.replace('%EmpEmployerPhone (Client)%', rec.EmpEmployerPhone);
                        decodeTemp = decodeTemp.replace('%EmpContactPerson (Client)%', rec.EmpContactPerson);
                        decodeTemp = decodeTemp.replace('%EmpWorkAddress (Client)%', rec.EmpWorkAddress);
                        decodeTemp = decodeTemp.replace('%comesfrom (Client)%', rec.comesfrom);

                        //Loan Fileds
                        decodeTemp = decodeTemp.replace('%LoanID (Loan)%', rec.LoanID);
                        decodeTemp = decodeTemp.replace('%LoanNumber (Loan)%', rec.LoanNumber);
                        decodeTemp = decodeTemp.replace('%PaymentPeriod (Loan)%', rec.PaymentPeriod);
                        decodeTemp = decodeTemp.replace('%DrawDownDate (Loan)%', rec.DrawDownDate);
                        decodeTemp = decodeTemp.replace('%LoanStatusID (Loan)%', rec.LoanStatusID);
                        decodeTemp = decodeTemp.replace('%LoanTerm (Loan)%', rec.LoanTerm);
                        decodeTemp = decodeTemp.replace('%FirstPaymentDue (Loan)%', rec.FirstPaymentDue);
                        decodeTemp = decodeTemp.replace('%LowerRate (Loan)%', rec.LowerRate);
                        decodeTemp = decodeTemp.replace('%HigherRate (Loan)%', rec.HigherRate);
                        decodeTemp = decodeTemp.replace('%InterestMethod (Loan)%', rec.InterestMethod);
                        decodeTemp = decodeTemp.replace('%app_id (Loan)%', rec.app_id);
                        decodeTemp = decodeTemp.replace('%Lender (Loan)%', rec.Lender);
                        decodeTemp = decodeTemp.replace('%Product (Loan)%', rec.Product);
                        decodeTemp = decodeTemp.replace('%Type (Loan)%', rec.Type);
                        decodeTemp = decodeTemp.replace('%Purpose (Loan)%', rec.Purpose);
                        decodeTemp = decodeTemp.replace('%LoanAmount (Loan)%', rec.LoanAmount);
                        decodeTemp = decodeTemp.replace('%DishonorFee (Loan)%', rec.DishonorFee);
                        decodeTemp = decodeTemp.replace('%Memo (Loan)%', rec.Memo);
                        decodeTemp = decodeTemp.replace('%NewDDRDate (Loan)%', rec.NewDDRDate);
                        decodeTemp = decodeTemp.replace('%BankAccDate (Loan)%', rec.BankAccDate);
                        decodeTemp = decodeTemp.replace('%PaymentSchDate (Loan)%', rec.PaymentSchDate);
                        decodeTemp = decodeTemp.replace('%EffectiveDate (Loan)%', rec.EffectiveDate);
                        decodeTemp = decodeTemp.replace('%DefaultNotice (Loan)%', rec.DefaultNotice);
                        decodeTemp = decodeTemp.replace('%DoubleChecked (Loan)%', rec.DoubleChecked);
                        decodeTemp = decodeTemp.replace('%CreateDate (Loan)%', rec.CreateDate);
                        decodeTemp = decodeTemp.replace('%EditDate (Loan)%', rec.EditDate);
                        decodeTemp = decodeTemp.replace('%LastResult (Loan)%', rec.LastResult);
                        decodeTemp = decodeTemp.replace('%EzidebitRefNo (Loan)%', rec.EzidebitRefNo);
                        decodeTemp = decodeTemp.replace('%OperatorName%', EmailOpr);
                        tinymce.get('txtMailMessage').setContent(decodeTemp);
                    });
                }
            });
        }

    </script>
</body>
</html>
